from django.shortcuts import render

# Create your views here.
from rest_framework import status
from rest_framework.generics import CreateAPIView

from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_jwt.settings import api_settings

from oauth.exceptions import QQAPIError
from oauth.models import OAuthQQUser
from oauth.serializer import OAuthQQUserSerializer
from oauth.utils import OAuthQQ
from carts.utils import merge_cart_cookie_to_redis

# 第一步,前端获取qq登陆url
#  url(r'^qq/authorization/$', views.QQAuthURLView.as_view()),
class QQAuthURLView(APIView):
    """
    第一步获取QQ登录的url
    """
    def get(self, request):
        """
        提供用于qq登录的url
        """
        next = request.query_params.get('next')
        oauth = OAuthQQ(state=next)
        login_url = oauth.get_qq_login_url()
        # login_url = OAuthQQ.get_qq_login_url()
        return Response({'login_url': login_url})


# 第二步get,携带code与state,获取access_token,和openid
# 第三步post,绑定用户
class QQAuthUserView(CreateAPIView):
    """
    QQ登录的用户
    """
    serializer_class = OAuthQQUserSerializer

    def get(self, request):

        # 获取code
        code = request.query_params.get('code')
        if not code:
            return Response({'message': '缺少code'}, status=status.HTTP_400_BAD_REQUEST)

        # 凭借code获取access_token, 在工具类中获取
        # 凭借access_token获取oppenid
        oauth_qq = OAuthQQ()
        try:
            access_token = oauth_qq.get_access_token(code)
            openid = oauth_qq.get_openid(access_token)
        except QQAPIError:
            return Response({'message': '访问qq接口异常'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)

        # 根据oppenid查询数据库判断数据是否存在记录
        try:
            oauth_qq_user = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # 如果数据不存在, 处理openid为自己的access_token
            accesstoken = oauth_qq.generate_save_user_token(openid)
            return Response({'access_token': accesstoken})

        else:
            # 如果数据存在, 表示用户已经绑定过身份,签发JWT_token
            user = oauth_qq_user.user
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            # 登陆成功,返回三个字段
            # return Response({
            #     'username': user.username,
            #     'user_id': user.id,
            #     'token': token
            # })

            response = Response({
                'username': user.username,
                'user_id': user.id,
                'token': token
            })

            # qq登陆返回之前,先合并购物车
            response = merge_cart_cookie_to_redis(request, user, response)

            return response

    def post(self, request, *args, **kwargs):
        # 继承父类的post方法,添加合并购物车程序
        response = super().post(request, *args, **kwargs)

        # 合并购物车
        # 序列化器中视图对象中动添加user
        user = self.user
        response = merge_cart_cookie_to_redis(request, user, response)

        return response



    # 直接继承 CreatAPIView,就行了
    # 下面的逻辑在序列化器中写
    # def post(self, request):
    #     # 获取数据
    #
    #     # 校验数据
    #
    #     # 判断用户是否存在
    #     # 存在,绑定,创建QQAuthUserView
    #
    #     # 不存在,先创建用户,再创建QQAuthUserView
    #
    #     # 签发JWT_TOKEN









